package com.leetcode.sorts.hash;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: WuPeng
 * @Date: 2021/5/27 4:37 下午
 *
 * 15: 三数之和
 *
 */
public class ThreadSums_15 {

    public static List<List<Integer>> solution(int[] arr){
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(arr);
        int len = arr.length;
        for (int i = 0; i < len; i++) {

            if (arr[i] > 0) return result;

            if (i>0 && arr[i] == arr[i-1]) continue;

            int slow = i+1, fast = len-1;
            while (slow<fast) {
                int sum = arr[i] + arr[slow] + arr[fast];
                if (sum < 0){
                    slow++;
                }
                else if (sum > 0){
                    fast--;
                }
                else {
                    result.add(Arrays.asList(arr[i], arr[slow], arr[fast]));
                    while (slow < fast && arr[slow] == arr[slow+1]) slow++;
                    while (slow < fast && arr[fast] == arr[fast-1]) fast--;
                    slow++;
                    fast--;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] nums = {-1, 0, 1, 2, -1, -4};
        List<List<Integer>> solution = solution(nums);
        System.out.println(Arrays.toString(solution.toArray()));
    }

}
